package com.kang.user.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * 自定义请求拦截器
 *
 * 将旧请求中的请求头和 Cookie 数据复制到新的 Feign 请求中。
 */
@Configuration
public class MyRequestInterceptor implements RequestInterceptor {

	/**
	 * 拦截并处理请求
	 *
	 * @param template Feign 创建的新请求模板
	 */
	@Override
	public void apply(RequestTemplate template) {
		// 获取当前请求上下文中的旧请求对象
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (requestAttributes == null) {
			return;
		}

		HttpServletRequest request = requestAttributes.getRequest();

		// 获取请求头中的用户名
		Optional.ofNullable(request.getHeader("username"))
				.ifPresent(username -> template.header("username", username));

		// 获取 Cookie 数组并提取指定的 Cookie 值
		Optional.ofNullable(request.getCookies())
				.ifPresent(cookies -> {
					for (Cookie cookie : cookies) {
						if ("c1".equals(cookie.getName())) {
							template.header("c1", cookie.getValue());
							break;
						}
					}
				});
	}
}
